package com.exp.controller;

import com.exp.dto.UpdatePwdDTO;
import com.exp.pojo.UserInf;
import com.exp.result.Result;
import com.exp.result.StatusCode;
import com.exp.service.UserInfService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 修改密码模块-pyz
 */
@RestController
@RequestMapping("/admin/updatepwd")
@Slf4j
public class UpdatepwdController {

    @Autowired
    private UserInfService userInfService;

    @PutMapping("/updatePassword")
    public Result<UserInf> updatePassword(@RequestBody UpdatePwdDTO updatePwdDTO) {
        try {

            boolean isCurrentPasswordCorrect = userInfService.checkCurrentPassword(updatePwdDTO.getId(), updatePwdDTO.getCurrentPassword());
            if (!isCurrentPasswordCorrect) {
                return Result.error(StatusCode.ERROR, "当前密码不正确");
            }

            boolean isUpdated = userInfService.updatePassword(updatePwdDTO.getId(), updatePwdDTO.getNewPassword());

            if (isUpdated) {
                UserInf userInf = userInfService.getById(updatePwdDTO.getId());
                userInf.setPassword("*******");
                return Result.success(StatusCode.SUCCESS, "密码更新成功",userInf);
            } else {
                return Result.error(StatusCode.ERROR, "密码更新失败");
            }
        } catch (Exception e) {
            log.error("更新密码失败", e);
            return Result.error(StatusCode.ERROR, "更新密码过程中发生错误");
        }
    }
}
